<template>
  <div class="fund-research-container">
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="基金名称/代码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="基金类型">
          <el-select v-model="searchForm.type" placeholder="全部" clearable>
            <el-option v-for="item in fundTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="基金评级">
          <el-select v-model="searchForm.rating" placeholder="全部" clearable>
            <el-option v-for="item in ratingOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="searchForm.tag" placeholder="全部" clearable>
            <el-option v-for="item in tagOptions" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="fund-list-card">
      <template #header>
        <div class="card-header">
          <span>基金列表</span>
          <el-button type="primary" @click="handleAddFund">添加基金</el-button>
        </div>
      </template>
      <el-table :data="fundList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="code" label="基金代码" width="100" />
        <el-table-column prop="name" label="基金名称" min-width="180" />
        <el-table-column prop="type" label="基金类型" width="100" />
        <el-table-column prop="nav" label="最新净值" width="100">
          <template #default="scope">
            {{ scope.row.nav ? scope.row.nav.toFixed(4) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyReturn" label="日涨跌幅" width="100">
          <template #default="scope">
            <span :class="getReturnClass(scope.row.dailyReturn)">
              {{ scope.row.dailyReturn ? (scope.row.dailyReturn * 100).toFixed(2) + '%' : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="weeklyReturn" label="周涨跌幅" width="100">
          <template #default="scope">
            <span :class="getReturnClass(scope.row.weeklyReturn)">
              {{ scope.row.weeklyReturn ? (scope.row.weeklyReturn * 100).toFixed(2) + '%' : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="monthlyReturn" label="月涨跌幅" width="100">
          <template #default="scope">
            <span :class="getReturnClass(scope.row.monthlyReturn)">
              {{ scope.row.monthlyReturn ? (scope.row.monthlyReturn * 100).toFixed(2) + '%' : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="yearlyReturn" label="年涨跌幅" width="100">
          <template #default="scope">
            <span :class="getReturnClass(scope.row.yearlyReturn)">
              {{ scope.row.yearlyReturn ? (scope.row.yearlyReturn * 100).toFixed(2) + '%' : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评级" width="80">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" min-width="150">
          <template #default="scope">
            <el-tag
              v-for="tag in scope.row.tags"
              :key="tag.id"
              size="small"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ tag.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleViewFund(scope.row)">查看</el-button>
            <el-button link type="primary" size="small" @click="handleEditFund(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDeleteFund(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑基金对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加基金' : '编辑基金'"
      width="650px"
    >
      <el-form :model="fundForm" :rules="rules" ref="fundFormRef" label-width="100px">
        <el-form-item label="基金代码" prop="code">
          <el-input v-model="fundForm.code" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="基金名称" prop="name">
          <el-input v-model="fundForm.name" />
        </el-form-item>
        <el-form-item label="基金类型" prop="type">
          <el-select v-model="fundForm.type" placeholder="请选择基金类型">
            <el-option v-for="item in fundTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="最新净值" prop="nav">
          <el-input-number v-model="fundForm.nav" :precision="4" :step="0.0001" :min="0" />
        </el-form-item>
        <el-form-item label="日涨跌幅" prop="dailyReturn">
          <el-input-number v-model="fundForm.dailyReturn" :precision="4" :step="0.0001" />
        </el-form-item>
        <el-form-item label="周涨跌幅" prop="weeklyReturn">
          <el-input-number v-model="fundForm.weeklyReturn" :precision="4" :step="0.0001" />
        </el-form-item>
        <el-form-item label="月涨跌幅" prop="monthlyReturn">
          <el-input-number v-model="fundForm.monthlyReturn" :precision="4" :step="0.0001" />
        </el-form-item>
        <el-form-item label="年涨跌幅" prop="yearlyReturn">
          <el-input-number v-model="fundForm.yearlyReturn" :precision="4" :step="0.0001" />
        </el-form-item>
        <el-form-item label="基金规模" prop="size">
          <el-input-number v-model="fundForm.size" :precision="2" :step="0.01" :min="0" />
        </el-form-item>
        <el-form-item label="基金经理" prop="manager">
          <el-input v-model="fundForm.manager" />
        </el-form-item>
        <el-form-item label="基金公司" prop="company">
          <el-input v-model="fundForm.company" />
        </el-form-item>
        <el-form-item label="评级" prop="rating">
          <el-rate v-model="fundForm.rating" />
        </el-form-item>
        <el-form-item label="基金描述" prop="description">
          <el-input type="textarea" v-model="fundForm.description" :rows="3" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="fundForm.selectedTags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或创建标签"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看基金详情对话框 -->
    <el-dialog v-model="detailVisible" title="基金详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="基金代码">{{ currentFund.code }}</el-descriptions-item>
        <el-descriptions-item label="基金名称">{{ currentFund.name }}</el-descriptions-item>
        <el-descriptions-item label="基金类型">{{ currentFund.type }}</el-descriptions-item>
        <el-descriptions-item label="最新净值">{{ currentFund.nav }}</el-descriptions-item>
        <el-descriptions-item label="日涨跌幅">
          <span :class="getReturnClass(currentFund.dailyReturn)">
            {{ currentFund.dailyReturn ? (currentFund.dailyReturn * 100).toFixed(2) + '%' : '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="周涨跌幅">
          <span :class="getReturnClass(currentFund.weeklyReturn)">
            {{ currentFund.weeklyReturn ? (currentFund.weeklyReturn * 100).toFixed(2) + '%' : '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="月涨跌幅">
          <span :class="getReturnClass(currentFund.monthlyReturn)">
            {{ currentFund.monthlyReturn ? (currentFund.monthlyReturn * 100).toFixed(2) + '%' : '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="年涨跌幅">
          <span :class="getReturnClass(currentFund.yearlyReturn)">
            {{ currentFund.yearlyReturn ? (currentFund.yearlyReturn * 100).toFixed(2) + '%' : '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="基金规模">{{ currentFund.size }} 亿元</el-descriptions-item>
        <el-descriptions-item label="基金经理">{{ currentFund.manager }}</el-descriptions-item>
        <el-descriptions-item label="基金公司">{{ currentFund.company }}</el-descriptions-item>
        <el-descriptions-item label="评级">
          <el-rate v-model="currentFund.rating" disabled text-color="#ff9900" />
        </el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <el-tag
            v-for="tag in currentFund.tags"
            :key="tag.id"
            size="small"
            style="margin-right: 5px"
          >
            {{ tag.name }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="基金描述" :span="2">
          {{ currentFund.description }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getAllFunds, 
  getFundsByType, 
  getFundsByRating, 
  getFundsByTypeAndRating, 
  getFundsByTagName,
  searchFunds,
  createFund,
  updateFund,
  deleteFund 
} from '@/api/fund';
import axios from 'axios';

export default {
  name: 'FundResearch',
  setup() {
    const loading = ref(false);
    const fundList = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const dialogVisible = ref(false);
    const detailVisible = ref(false);
    const dialogType = ref('add'); // 'add' 或 'edit'
    const fundFormRef = ref(null);
    const currentFund = ref({});

    const fundTypes = [
      { value: '股票型', label: '股票型' },
      { value: '混合型', label: '混合型' },
      { value: '债券型', label: '债券型' },
      { value: '指数型', label: '指数型' },
      { value: 'QDII', label: 'QDII' },
      { value: 'FOF', label: 'FOF' },
      { value: '货币型', label: '货币型' }
    ];

    const ratingOptions = [
      { value: 5, label: '五星' },
      { value: 4, label: '四星' },
      { value: 3, label: '三星' },
      { value: 2, label: '二星' },
      { value: 1, label: '一星' }
    ];

    const tagOptions = ref([
      { id: 1, name: '低风险' },
      { id: 2, name: '中风险' },
      { id: 3, name: '高风险' },
      { id: 4, name: '价值投资' },
      { id: 5, name: '成长投资' },
      { id: 6, name: '稳健型' },
      { id: 7, name: '激进型' },
      { id: 8, name: '蓝筹' },
      { id: 9, name: '科技' },
      { id: 10, name: '医疗健康' },
      { id: 11, name: '消费' },
      { id: 12, name: '主动管理' },
      { id: 13, name: '被动管理' },
      { id: 14, name: '中小盘' },
      { id: 15, name: '大盘' }
    ]);

    const searchForm = reactive({
      keyword: '',
      type: '',
      rating: '',
      tag: ''
    });

    const fundForm = reactive({
      id: null,
      code: '',
      name: '',
      type: '',
      nav: null,
      dailyReturn: null,
      weeklyReturn: null,
      monthlyReturn: null,
      yearlyReturn: null,
      size: null,
      manager: '',
      company: '',
      description: '',
      rating: 3,
      selectedTags: [], // 选中的标签ID
      tags: [] // 实际的标签对象数组
    });

    const rules = {
      code: [
        { required: true, message: '请输入基金代码', trigger: 'blur' },
        { min: 6, max: 6, message: '基金代码长度应为6个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入基金名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择基金类型', trigger: 'change' }
      ],
      nav: [
        { required: true, message: '请输入最新净值', trigger: 'blur' }
      ]
    };

    // 计算分页后的数据
    const paginatedFundList = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return fundList.value.slice(start, end);
    });

    // 初始化获取数据
    const fetchFunds = async () => {
      loading.value = true;
      try {
        console.log('尝试从API获取数据...');
        
        // 先测试简单的API端点
        try {
          const testResponse = await axios.get('http://localhost:8080/api/funds/test');
          console.log('测试API响应:', testResponse.data);
        } catch (testError) {
          console.error('测试API失败:', testError);
        }
        
        // 直接使用axios请求，绕过封装
        const response = await axios.get('http://localhost:8080/api/funds');
        console.log('API响应成功:', response);
        
        // 继续使用正常流程
        const res = await getAllFunds();
        fundList.value = res;
        total.value = res.length;
      } catch (error) {
        console.error('获取基金列表失败，错误详情:', error);
        if (error.response) {
          console.log('错误响应状态:', error.response.status);
          console.log('错误响应数据:', error.response.data);
        }
        ElMessage.error('获取基金列表失败，请查看控制台详细错误信息');
        
        // 使用模拟数据
        fundList.value = [
          {
            id: 1,
            code: '000001',
            name: '示例平衡型基金',
            type: '混合型',
            nav: 1.2345,
            dailyReturn: 0.0123,
            weeklyReturn: 0.0234,
            monthlyReturn: 0.0345,
            yearlyReturn: 0.1234,
            size: 10.5,
            manager: '张三',
            company: '示例基金公司',
            description: '这是一个平衡型基金，适合稳健型投资者。',
            rating: 4,
            tags: [
              { id: 2, name: '中风险' },
              { id: 4, name: '价值投资' },
              { id: 7, name: '主动管理' }
            ]
          },
          {
            id: 2,
            code: '000002',
            name: '示例成长型基金',
            type: '股票型',
            nav: 1.5678,
            dailyReturn: 0.0234,
            weeklyReturn: 0.0345,
            monthlyReturn: 0.0456,
            yearlyReturn: 0.2345,
            size: 15.2,
            manager: '李四',
            company: '示例基金公司',
            description: '这是一个成长型基金，专注于高增长企业。',
            rating: 5,
            tags: [
              { id: 3, name: '高风险' },
              { id: 5, name: '成长投资' },
              { id: 7, name: '主动管理' },
              { id: 10, name: '中小盘' }
            ]
          },
          {
            id: 3,
            code: '000003',
            name: '示例指数型基金',
            type: '指数型',
            nav: 1.0123,
            dailyReturn: 0.0111,
            weeklyReturn: 0.0222,
            monthlyReturn: 0.0333,
            yearlyReturn: 0.1111,
            size: 25.8,
            manager: '王五',
            company: '示例基金公司',
            description: '这是一个指数型基金，跟踪特定市场指数。',
            rating: 3,
            tags: [
              { id: 2, name: '中风险' },
              { id: 6, name: '指数型' },
              { id: 8, name: '被动管理' },
              { id: 9, name: '大盘' }
            ]
          },
          {
            id: 4,
            code: '000004',
            name: '示例债券型基金',
            type: '债券型',
            nav: 1.0456,
            dailyReturn: 0.0022,
            weeklyReturn: 0.0033,
            monthlyReturn: 0.0055,
            yearlyReturn: 0.0456,
            size: 8.6,
            manager: '赵六',
            company: '示例基金公司',
            description: '这是一个债券型基金，投资各类债券。',
            rating: 3,
            tags: [
              { id: 1, name: '低风险' },
              { id: 4, name: '价值投资' }
            ]
          },
          {
            id: 5,
            code: '000005',
            name: '示例科技行业基金',
            type: '股票型',
            nav: 1.8765,
            dailyReturn: 0.0345,
            weeklyReturn: 0.0567,
            monthlyReturn: 0.0789,
            yearlyReturn: 0.3456,
            size: 12.3,
            manager: '钱七',
            company: '示例基金公司',
            description: '这是一个科技行业基金，专注于科技企业投资。',
            rating: 4,
            tags: [
              { id: 3, name: '高风险' },
              { id: 5, name: '成长投资' },
              { id: 7, name: '主动管理' }
            ]
          }
        ];
        total.value = fundList.value.length;
      } finally {
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = async () => {
      loading.value = true;
      try {
        let res = [];

        if (searchForm.keyword) {
          res = await searchFunds(searchForm.keyword);
        } else if (searchForm.type && searchForm.rating) {
          res = await getFundsByTypeAndRating(searchForm.type, searchForm.rating);
        } else if (searchForm.type) {
          res = await getFundsByType(searchForm.type);
        } else if (searchForm.rating) {
          res = await getFundsByRating(searchForm.rating);
        } else if (searchForm.tag) {
          res = await getFundsByTagName(searchForm.tag);
        } else {
          res = await getAllFunds();
        }

        fundList.value = res;
        total.value = res.length;
        currentPage.value = 1;
      } catch (error) {
        console.error('搜索基金失败:', error);
        ElMessage.error('搜索基金失败');
      } finally {
        loading.value = false;
      }
    };

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
      });
      fetchFunds();
    };

    // 表格操作
    const handleAddFund = () => {
      dialogType.value = 'add';
      resetForm();
      dialogVisible.value = true;
    };

    const handleEditFund = (row) => {
      dialogType.value = 'edit';
      Object.assign(fundForm, row);
      fundForm.selectedTags = row.tags ? row.tags.map(tag => tag.id) : [];
      dialogVisible.value = true;
    };

    const handleViewFund = (row) => {
      currentFund.value = row;
      detailVisible.value = true;
    };

    const handleDeleteFund = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除基金"${row.name}"（代码：${row.code}）吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        try {
          await deleteFund(row.id);
          ElMessage.success('基金删除成功');
          // 重新加载数据
          fetchFunds();
        } catch (error) {
          if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
          } else if (error.message.includes('active portfolio')) {
            ElMessage.error('无法删除：该基金正在被使用的投资组合中');
          } else if (error.message.includes('pending transactions')) {
            ElMessage.error('无法删除：该基金有未完成的交易');
          } else {
            ElMessage.error('删除基金失败，请稍后重试');
          }
        }
      } catch {
        // 用户取消删除操作
      }
    };

    // 表单提交
    const submitForm = async () => {
      if (!fundFormRef.value) return;
      
      await fundFormRef.value.validate(async (valid) => {
        if (valid) {
          // 处理表单数据
          const formData = { ...fundForm };
          
          // 将选中的标签ID转换为标签对象
          formData.tags = formData.selectedTags.map(tagId => {
            const tag = tagOptions.value.find(t => t.id === tagId);
            return { id: tag.id, name: tag.name };
          });
          
          delete formData.selectedTags;
          
          try {
            if (dialogType.value === 'add') {
              await createFund(formData);
              ElMessage.success('添加成功');
            } else {
              await updateFund(formData.id, formData);
              ElMessage.success('更新成功');
            }
            dialogVisible.value = false;
            fetchFunds();
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加基金失败:' : '更新基金失败:', error);
            ElMessage.error(dialogType.value === 'add' ? '添加基金失败' : '更新基金失败');
          }
        } else {
          ElMessage.error('请完善表单信息');
          return false;
        }
      });
    };

    const resetForm = () => {
      if (fundFormRef.value) {
        fundFormRef.value.resetFields();
      }
      Object.assign(fundForm, {
        id: null,
        code: '',
        name: '',
        type: '',
        nav: null,
        dailyReturn: null,
        weeklyReturn: null,
        monthlyReturn: null,
        yearlyReturn: null,
        size: null,
        manager: '',
        company: '',
        description: '',
        rating: 3,
        selectedTags: [],
        tags: []
      });
    };

    // 涨跌颜色
    const getReturnClass = (value) => {
      if (!value) return '';
      return value > 0 ? 'positive-return' : value < 0 ? 'negative-return' : '';
    };

    // 分页操作
    const handleSizeChange = (size) => {
      pageSize.value = size;
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    onMounted(() => {
      fetchFunds();
    });

    return {
      loading,
      fundList,
      currentPage,
      pageSize,
      total,
      paginatedFundList,
      dialogVisible,
      detailVisible,
      dialogType,
      fundFormRef,
      currentFund,
      fundTypes,
      ratingOptions,
      tagOptions,
      searchForm,
      fundForm,
      rules,
      fetchFunds,
      handleSearch,
      resetSearch,
      handleAddFund,
      handleEditFund,
      handleViewFund,
      handleDeleteFund,
      submitForm,
      resetForm,
      getReturnClass,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.fund-research-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.fund-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.positive-return {
  color: #f56c6c;
}

.negative-return {
  color: #67c23a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 